<?php
/**
 * Created by PhpStorm.
 * User: soosoogoo
 * Date: 4/16
 * Time: 23:52
 */
namespace Library\Client;

use Helper\Helper;

class Curl
{
    /**
     * 以post方式提交data到对应的接口url
     * @param string $url url
     * @param array $data 需要post的数据
     * @param int $second url执行超时时间，默认200ms
     * @return int|mixed|string
     */
    public static function postCurl($url, $data = array(), $second = 3000)
    {

        $st = time();

        $ch = curl_init();

        //请求头加上 客户端IP
        //$clientIp = Helper::getClientIp();
        $headers = array(
            "Content-type: application/json;charset='utf-8'",
            "Accept: application/json",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
        );

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        //设置过期时间毫秒
        curl_setopt($ch, CURLOPT_NOSIGNAL, true);    //注意，毫秒超时一定要设置这个
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, $second); //超时时间200毫秒 低版本 毫秒小于 存在bug

        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);        //curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); 返回错误码为 60时             #TRUE
        //curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//严格校验//curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); 返回错误码为 60时    #2
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //运行curl
        $data = curl_exec($ch);

        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $et = time();
            $error = curl_errno($ch);
            $costTime = $et-$st;
            curl_close($ch);
            return -$error;
        }
    }
}